import React, { Component } from 'react'
import { Table, Button,Modal,Form, Input,Select,Tag} from 'antd'
import { SearchOutlined ,
          DeleteOutlined
} from '@ant-design/icons'
import axios from 'axios'
//import store from '../../redux/store'
import { getlist } from '../../redux/action/getlist'
import {connect} from 'react-redux'

const { Option } = Select
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};


const onFinish = values => {
  console.log('Success:', values);
};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};

 class Recipe extends Component {
    componentDidMount() {
      if(this.props.relist.length===0){
        this.props.getlist()
      }else{
        console.log("使用缓存")
      }

      //console.log(getlist())
      // if(store.getState().relist.length===0){
      //   store.dispatch(getlist()).then(res=>{
      //     console.log(store.getState().relist)
      //    this.setState({
      //      datalist:store.getState().relist
      //    })

      //   })
      // }else{
      //   console.log("使用缓存")
      //   this.setState({
      //     datalist:store.getState().relist
      //   })

      // }
      

        axios.get('http://localhost:5000/Cuisine').then(res=>{
          //console.log(res.data)
          this.setState({
            recipeList:res.data
          })
        })
    }
    
    state={
      currentitem:{},
       recipeList:[],
       visible: false,
       visible1: false,
       dataform:"",
        columns:[
           
            {
              title: '菜系',
              dataIndex: 'cooking',
              key: 'cooking',
            },
            {
              title: '菜名',
              dataIndex: 'name',
              key: 'name',
              render:(text,data)=>{
              //  console.log(data)
                let divcolor =["red","pink","green","blue","yellow","skyblue","yellowgreen","black"]
                let caixi=["川菜","湘菜","粤菜","浙菜","苏菜","鲁菜","闽菜","徽菜"]
                let num = caixi.indexOf(data.cooking)
                //console.log( caixi.indexOf("川菜"))
               return (
                <Tag color={divcolor[num]}>{text}</Tag>
               )
              }
              
            },
            {
              title: '口味',
              dataIndex: 'flavor',
              key: 'flavor',
            },
            {
              title: 'action',
              dataIndex: '',
              key: 'action',
              render:item=>{
                return <div>
                  <Button type="primary" shape="circle" icon={<SearchOutlined />} 
                  onClick={()=>this.handUpdate(item)}/>
                  <Button type="danger" shape="circle" icon={<DeleteOutlined />} 
                  onClick={()=>this.handDele(item)}/>
                </div>
              }
            },
            
        ],
        datalist:[]

    }
    render() {
        return (
            <div>
                <Button type="primary" onClick={this.handAdd}>添加菜品</Button>
                {/* 创建modal */}
                <Modal
                  title="Basic Modal"
                  visible={this.state.visible}
                  onOk={this.handleOk}
                  onCancel={this.handleCancel}
                >
                        <Form
                        {...layout}
                        name="basic"
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        ref="myform"
                      >
                        <Form.Item
                          label="菜系"
                          name="cooking"
                          rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                          <Select
                              showSearch
                              style={{ width: 200 }}
                              placeholder="选择喜爱的菜系"
                            >{
                              this.state.recipeList.map(item=>{
                                return <Option value={item.name} key={item.id}>{item.name}</Option>
                                
                             })
                            }
                            </Select>
                        </Form.Item>

                        <Form.Item
                          label="菜名"
                          name="name"
                          rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                          <Input/>
                        </Form.Item>
                        <Form.Item
                          label="口味"
                          name="flavor"
                          rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                          <Input/>
                        </Form.Item>

                    </Form>
                </Modal>
                        {/* 更新 */}
                <Modal
                  title="Basic Modal"
                  visible={this.state.visible1}
                  onOk={this.handleOkupdate}
                  onCancel={this.handleCancelupdate}
                >
                        <Form
                        {...layout}
                        name="basic"
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        ref="updatefrom"
                      >
                        <Form.Item
                          label="菜系"
                          name="cooking"
                          rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                          <Select
                              showSearch
                              style={{ width: 200 }}
                              placeholder="选择喜爱的菜系"
                            >{
                              this.state.recipeList.map(item=>{
                                return <Option value={item.name} key={item.id}>{item.name}</Option>
                                
                             })
                            }
                            </Select>
                        </Form.Item>

                        <Form.Item
                          label="菜名"
                          name="name"
                          rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                          <Input/>
                        </Form.Item>
                        <Form.Item
                          label="口味"
                          name="flavor"
                          rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                          <Input/>
                        </Form.Item>

                    </Form>
                </Modal>
                
                <Table columns={this.state.columns} dataSource={this.props.relist} 
                rowKey={item=>item.id} pagination={{pageSize:5}}/>
            </div>
        )
    }
   
       
      

    //创建菜谱按钮
    handAdd=()=>{
      //console.log("dianji")
      this.setState({
        visible:true
      })
    }
    //点击ok
    handleOk = e => {
      //console.log(this.refs.myform)
      this.refs.myform.validateFields().then(res=>{
        //console.log(res)
        this.setState({
          dataform:res,
          
        })
        axios.post('http://localhost:5000/flavoured',{
              ...this.state.dataform,
              craft:"",
              food:""
         }).then(res=>{
              this.setState({
                visible: false,
              datalist:[...this.state.datalist,res.data]
              })
      })
      //表单重置
      this.refs.myform.resetFields()
      })
     
    };
    //点击cancel
    handleCancel = e =>{
      this.setState({
        visible: false,
      })
    }

    handUpdate=(item)=>{
      console.log(item)
      setTimeout(()=>{
        this.refs.updatefrom.setFieldsValue({
          cooking:item.cooking,
          name:item.name,
          flavor:item.flavor
        })
      },0)
      this.setState({
        visible1:true,
        currentitem:item
      })
    }

    handleCancelupdate=()=>{
      this.setState({
        visible1:false
      })
    }

    handleOkupdate=()=>{
      this.refs.updatefrom.validateFields().then(res=>{
        console.log(res)
        axios.put(`http://localhost:5000/flavoured/${this.state.currentitem.id}`,{
          ...this.state.currentitem,
          ...res
        }).then(res=>{
           this.setState({
             datalist:this.state.datalist.map(item=>{
               if(item.id===this.state.currentitem.id){
                 return res.data
               }else{
                 return item
               }
             })
           })
        })
      })
     
      this.setState({
        visible1:false
      })
    }

    handDele=(item)=>{
      axios.delete(`http://localhost:5000/flavoured/${item.id}`).then(res=>{
          this.setState({
              datalist:this.state.datalist.filter(data=>data.id!==item.id)
          })
      })
  }
}

const mapstateToProps=(state)=>{
  console.log(state)
return {
  relist:state.relist
}
}

const mapdispathToProps={
  getlist
}

export default connect(mapstateToProps,mapdispathToProps)(Recipe)